<?php
class ExtraToolController extends Zend_Controller_Action
{	
	public function init()
	{
		$this->_country	= $this->_request->getParam('cn');
	}
	
	public function indexAction()
	{
		exit;
	}
	
	public function intergratePoAction()
	{
		/*
			Intergrate data from CSV file (will be uploaded) & query
		*/
		if( $this->_request->isPost() )
		{
			set_time_limit(9999);
			ini_set('memory_limit', '-1');	
			
			$objFile		= isset($_FILES['file']) ? $_FILES['file'] : null ;
			
			$table			= $this->_country.'_intergrated_po';
			#From CSV
			$arrKey			= array('sku', 'uid', 'csv_cost', 'createdate', 'csv_type');
			$db				= Zend_Registry::get('db');
			$strQuery		= "
				DROP TABLE IF EXISTS `".$table."`;
				CREATE TABLE `".$table."` LIKE `_intergrated_po`;
				LOAD DATA LOCAL INFILE '".str_replace('\\', '/', $objFile['tmp_name'])."' 
					INTO TABLE `".$table."` 
					FIELDS TERMINATED BY ',' ENCLOSED BY '\"'
					LINES TERMINATED BY '\r\n'
					IGNORE 1 LINES
					(".implode(',', $arrKey).")
				";
			
			$db		= Zend_Registry::get('db');
			$db->execute($strQuery);
			#From CSV
			
			#From Query
			$strQuery	= '
				SELECT 
					distinct invh.uid, prod.sku, invh.cost, invh.created_at, poi.cost as `PO_Cost`, po.created_at,
					invh.po_type, po.fk_purchase_order_contract_type `PO_Contract_Type`
				FROM wms_inventory_history invh 
					INNER JOIN wms_inventory inv ON invh.uid = inv.uid
					LEFT OUTER JOIN ims_purchase_order_item poi ON invh.fk_purchase_order_item = poi.id_purchase_order_item 
					LEFT OUTER JOIN ims_purchase_order po ON poi.fk_purchase_order = po.id_purchase_order
					LEFT OUTER JOIN ims_product prod ON invh.fk_product = prod.id_product
				WHERE inv.fk_inventory_status = 1
				LIMIT 0,70000
			';
			
			$db_oms		= new Common_Db('wms_'.$this->_country);
			$arrData_Oms= $db_oms->fetchAll($strQuery);
			if($arrData_Oms)
			{
				$strQuery	= 'INSERT INTO `'.$table.'` (sku, uid, q_ivn_cost, q_po_cost, q_ivn_type, q_contract_type, createdate, itype) VALUES';
				$index		= 0;
				foreach($arrData_Oms as $data)
				{
					if($index>0){
						$strQuery	= $strQuery.',';
					}
					$strQuery		= $strQuery.'("'.trim($data['sku']).'", "'.trim($data['uid']).'", "'.trim($data['cost']).'", "'.trim($data['PO_Cost']).'", "'.trim($data['po_type']).'", "'.trim($data['PO_Contract_Type']).'", "'.trim($data['created_at']).'", 2)';
					$index++;
				}
	
				$db->execute($strQuery);
				$db->closeConnection();
				
				#Send Email
				$strHttpPath	= self::_save_export($this->_country, $arrData_Oms);
				$subject		= 'OMS Inventory ['.strtoupper($this->_country).'] at ['.date('Y-m-d H:i:s').']';
				$body			= $strHttpPath.'<br /><br /><strong>Right click</strong> on Link > choose <em><strong>Save link as</strong></em>';
				$email			= 'anil-kumar.singh@lazada.vn';
				CCommon::send_mail($subject, $body, $email);
				#Send Email
			}
			#From Query
			
			echo '<script>parent.update_done();</script>';
			exit;
		}
		$this->view->arrCountry	= CConfig::country_list();
	}
	
	public function downloadIntergratedPoAction()
	{
		if( $this->_request->isPost() )
		{
			set_time_limit(9999);
			ini_set('memory_limit', '-1');	
			
			$table			= $this->_country.'_intergrated_po';
			$strQuery		= 'SELECT * FROM `'.$table.'`';
			$db				= Zend_Registry::get('db');
			$arrResult		= $db->fetchAll($strQuery);
			if($arrResult){
				self::_download_export($this->_country, $arrResult);
			}
		}
		exit;
	}
	
	static function _save_export($p_strCountry, $p_arrResult)
	{
		$strPath	= ROOT_SITE.'/static';
		$strPath	= $strPath.'/extra-tool';
		@mkdir($strPath);
		$strPath	= $strPath.'/oms-po';
		@mkdir($strPath);
		$strPath	= $strPath.'/'.date('Y');
		@mkdir($strPath);
		$strPath	= $strPath.'/'.date('m');
		@mkdir($strPath);
		$strPath	= $strPath.'/'.date('d');
		@mkdir($strPath);
		$strPath	= $strPath.'/'.$p_strCountry.'_'.date('His').'.csv';
		
		$fp 		= fopen($strPath, 'w');
		$arrTitle	= array();
		foreach($p_arrResult as $data)
		{
			foreach($data as $key=>$value){
				$arrTitle[]	= $key;
			}
			break;
		}
		fputcsv($fp, $arrTitle);
		foreach($p_arrResult as $data){
			fputcsv($fp, $data);
		}
		return str_replace(ROOT_SITE, HOST, $strPath);
	}
	
	static function _download_export($p_strCountry, $p_arrResult)
	{
		$arrTitle		= array();
		foreach($p_arrResult as $data)
		{
			foreach($data as $key=>$value){
				$arrTitle[]	= $key;
			}
			break;
		}
		
		$strFname	= $p_strCountry.'_intergrate_po_'.date('YmdHis');
		$strFname	= $strFname.'.csv';
		$strCSV		= null;
		$strCSV		= $strCSV. implode(';', $arrTitle)."\r\n";
		foreach($p_arrResult as $data)
		{
			$arrRecord		= array();
			foreach($data as $key=>$value){
				$arrRecord[]	= $value;
			}
			$strCSV	= $strCSV. implode(';', $arrRecord)."\r\n";
		}
		$strCSV = chr(255).chr(254).mb_convert_encoding($strCSV, "UTF-16LE", "UTF-8");	
		header("Content-type: application/ms-excel");
		header("Content-disposition: attachment; filename=".$strFname."; size=".strlen($strCSV));
		header('Cache-Control: max-age=0'); 
		echo $strCSV;
	}
}
?>
